# -*- coding: utf-8 -*-
__author__ = 'sunnychou'
__date__ = '2019/6/19 16:32'

import uuid
import datetime
import calendar

#根据得分得到工资等级评定和工资系数
def level_charge(avg_score):
    if avg_score >= 1.3:
        return ("A", 1.2)
    elif avg_score >= 1.1:
        return ("B", 1.1)
    elif avg_score >= 0.9:
        return ("C", 1.0)
    elif avg_score >= 0.7:
        return ("D", 0.9)
    else:
        return ("E", 0.8)


def format_float(input_float):
    if input_float == None:
        return 0
    return float("%.2f" % float(input_float))


def create_uuid():
    '''
    产生一个唯一标识，采用uuid库
    :return:
    '''
    return ''.join(str(uuid.uuid1()).split('-'))


def  filter_defaultdict_dict(cond_list, input_dict):
    '''
    从input_dict中选取cond_list列表中的元素
    :param cond_list: 条件列表
    :param input_dict:
    :return:
    '''
    user_score_dict = {}
    for  sname   in input_dict.keys():
        if sname not in set(cond_list):
            continue
        score = input_dict[sname]
        score = score[0] if isinstance(score, list) else score
        user_score_dict[sname]  = score
    return user_score_dict


def getMonthFirstDayAndLastDay(year=None, month=None):
    """
    :param year: 年份，默认是本年，可传int或str类型
    :param month: 月份，默认是本月，可传int或str类型
    :return: firstDay: 当月的第一天，datetime.date类型
              lastDay: 当月的最后一天，datetime.date类型
    """
    if year:
        year = int(year)
    else:
        year = datetime.date.today().year

    if month:
        month = int(month)
    else:
        month = datetime.date.today().month

    # 获取当月第一天的星期和当月的总天数
    firstDayWeekDay, monthRange = calendar.monthrange(year, month)
    # 获取当月的第一天
    firstDay = datetime.date(year=year, month=month, day=1)
    lastDay = datetime.date(year=year, month=month, day=monthRange)
    fday = f"{firstDay.year}-{addzero(firstDay.month)}-{addzero(firstDay.day)}"
    lday = f"{lastDay.year}-{addzero(lastDay.month)}-{addzero(lastDay.day)}"

    return fday, lday

def addzero(n):
    nabs = abs(int(n))
    if (nabs < 10):
        return "0" + str(nabs)
    else:
        return nabs

def get_days_of_month(year, mon):
    return calendar.monthrange(year, mon)[1]

#def getyearandmonth(n=0):
def getyearandmonth(ymonth, n=0):
    '''
    获取从ymonth年月开始，往n个月计算月份，得到开始时间和结束时间
    :param ymonth: 2019-09
    :param n: 往前或者往后多少个月
    :return:
    '''
    #thisyear = datetime.datetime.today().year
    #thismon = datetime.datetime.today().month
    thisyear = int(ymonth.split("-")[0])
    thismon = abs(int(ymonth.split("-")[1]))
    totalmon = thismon + n
    if (n >= 0):
        if (totalmon <= 12):
            days = str(get_days_of_month(thisyear, totalmon))
            totalmon = addzero(totalmon)
            return (datetime.datetime.today().year, totalmon, days)
        else:
            i = totalmon / 12
            j = totalmon % 12
            if (j == 0):
                i -= 1
                j = 12
            thisyear += i
            days = str(get_days_of_month(thisyear, j))
            j = addzero(j)
            return (str(thisyear), str(j), days)
    else:
        if ((totalmon > 0) and (totalmon < 12)):
            days = str(get_days_of_month(thisyear, totalmon))
            totalmon = addzero(totalmon)
            return (datetime.datetime.today().year, totalmon, days)
        else:
            i = totalmon / 12
            j = totalmon % 12
            if (j == 0):
                i -= 1
                j = 12
            thisyear += i
            days = str(get_days_of_month(thisyear, j))
            j = addzero(j)
        return (str(thisyear), str(j), days)

def get_today_month(ymonth, n=0):
    #day=datetime.datetime.today().day
    (y, m, d) = getyearandmonth(ymonth, n)
    (nfday, nlday) = getMonthFirstDayAndLastDay(y, m)
    return (nfday, nlday)

import datetime
from datetime import timedelta


def dformat(fdatetime):
    return "%s-%s-%s" % (str(fdatetime.year), addzero(fdatetime.month), str(addzero(fdatetime.day)))

class FVDateTime(object):
    #https://blog.csdn.net/wangxin6722513/article/details/78082593

    def __init__(self, input_month=None):
        '''
        :param input_month: 2019-06 字符串
        '''
        #now = datetime.datetime.now()
        now =  datetime.datetime.now() if input_month==None else datetime.datetime.strptime(input_month,'%Y-%m')
        # 本月第一天和最后一天
        self.__this_month_start = datetime.datetime(now.year, now.month, 1)
        print(f"now.month:{now.month}, type:{type(now.month)}")
        self.__this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1)  if now.month != 12  \
               else  datetime.datetime(now.year+1, 1, 1) - timedelta(days=1)
        # 上月第一天和最后一天
        self.__last_month_end = self.__this_month_start - timedelta(days=1)
        self.__last_month_start = datetime.datetime(self.__last_month_end.year, self.__last_month_end.month, 1)
        # 本季第一天和最后一天
        quarter_month = (now.month - 1) - (now.month - 1) % 3 + 1
        self.__this_quarter_start = datetime.datetime(now.year, quarter_month, 1)
        self.__this_quarter_end = datetime.datetime(now.year, quarter_month + 3, 1) - timedelta(days=1) if quarter_month < 10 \
            else   datetime.datetime(now.year+1, 1, 1) - timedelta(days=1)
        #本年第一天和最后一天
        self.__this_year_start = datetime.datetime(now.year, 1, 1)
        self.__this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1)
        #去年第一天
        self.__last_year_end = self.__this_year_start - timedelta(days=1)
        self.__last_year_start = datetime.datetime(self.__last_year_end.year, 1, 1)
        #去年上个月第一天和最后一天
        self.__last_year_lastmonth_start = datetime.datetime(self.__last_year_end.year,
                                                           self.__last_month_end.month, 1)
        self.__last_year_thismonth_start = datetime.datetime(self.__last_year_end.year, now.month, 1)
        self.__last_year_thismonth_end = datetime.datetime(self.__last_year_end.year, now.month+1, 1) - timedelta(days=1) if now.month != 12 \
                 else datetime.datetime(self.__last_year_end.year+1, 1, 1) - timedelta(days=1)
        self.__last_year_lastmonth_end = datetime.datetime(self.__last_year_end.year, self.__last_month_end.month+1, 1) - timedelta(days=1)  if self.__last_month_end.month != 12 \
                else datetime.datetime(self.__last_year_end.year+1, 1, 1) - timedelta(days=1)

        # 去年本季第一天和最后一天
        quarter_month = (self.__last_year_start.month - 1) - (self.__last_year_start.month - 1) % 3 + 1
        self.__last_year_quarter_start = datetime.datetime(self.__last_year_start.year, quarter_month, 1)
        self.__last_year_quarter_end = datetime.datetime(self.__last_year_start.year, quarter_month + 3, 1) - timedelta(days=1)  if quarter_month < 10 \
                else datetime.datetime(self.__last_year_start.year+1, 1, 1) - timedelta(days=1)


    def to_dict(self):
        '''
        唯一的外部可以访问数据的入口
        :return:
        '''
        return dict(
            this_month_start = dformat(self.__this_month_start),
            this_month_end = dformat(self.__this_month_end),
            last_month_start = dformat(self.__last_month_start),
            last_month_end = dformat(self.__last_month_end),
            this_quarter_start = dformat(self.__this_quarter_start),
            this_quarter_end = dformat(self.__this_quarter_end),
            this_year_start = dformat(self.__this_year_start),
            this_year_end = dformat(self.__this_year_end),
            last_year_start = dformat(self.__last_year_start),
            last_year_end = dformat(self.__last_year_end),
            last_year_thismonth_start = dformat(self.__last_year_thismonth_start),
            last_year_thismonth_end = dformat(self.__last_year_thismonth_end),
            last_year_lastmonth_start = dformat(self.__last_year_lastmonth_start),
            last_year_lastmonth_end = dformat(self.__last_year_lastmonth_end),
            last_year_quarter_start = dformat(self.__last_year_quarter_start),
            last_year_quarter_end = dformat(self.__last_year_quarter_end),
        )

def get_month(last_month_day):
    return f"{last_month_day.split('-')[0]}-{last_month_day.split('-')[1]}"

def series_value(series, key):
    '''
    获取series一维数组对应key的value
    :param series:
    :param key:
    :return:
    '''
    try:
        return series[key]
    except Exception as e:
        return 0

def increase_rate(this_value, last_value):
    '''
    计算同比增长率
    :param this_value:  当前月份（季度）值
    :param last_value:  去年同月分（季度）值
    :return:
    '''
    try:
        if this_value < 0 and last_value == 0:
            return  "-100%"
        elif this_value > 0 and last_value == 0:
            return "100%"
        elif this_value == 0 and last_value == 0:
            return 0
        increase_rate = "%.2f" % float(100 * (this_value - last_value) / last_value) + '%'
        return increase_rate
    except Exception as e:
        return 0


def get_lastyear_mouth(time):
    fvdate = FVDateTime(time)
    res = fvdate.to_dict()
    k = res['last_year_thismonth_start']
    end_time=get_month(k)
    return end_time


def get_thisyear_month_list(this_month):
    '''
    获取到目前月份为止的今年所有月份
    :param this_month: 输入的当前月份 2019-09
    :return:
    '''
    try:
        year = this_month.split("-")[0]
        month = this_month.split("-")[1]
        int_month = int(month)
        month_list = []
        for mt in  range(int_month):
            mt_month = f"{year}-{addzero(mt + 1)}"
            month_list.append(mt_month)
        return month_list
    except:
        return []


def get_quarter_index(this_month):
    '''
    获取季度索引
    :param this_month:
    :return:
    '''
    try:
        year = this_month.split("-")[0]
        month = this_month.split("-")[1]
        int_month = int(month)
        if int_month == 3:
            return 1
        elif int_month == 6:
            return 2
        elif int_month == 9:
            return 3
        elif int_month == 12:
            return 4
        return 0
    except:
        return 0

if __name__ == "__main__":
    #获取上个月
    # print(get_today_month(-4))
    # res = getMonthFirstDayAndLastDay()
    # print(res)
    res = get_thisyear_month_list('2019-08')
    print(res)
    for i, item in enumerate(res):
        print(i+1, item)

    print(get_quarter_list('2019-12'))